package com.thinkingcoder.tcrpc.core.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;

import com.thinkingcoder.tcrpc.core.listener.ApolloChangedListener;
import com.thinkingcoder.tcrpc.core.provider.ProviderBootstrap;
import com.thinkingcoder.tcrpc.core.provider.ProviderInvoker;
import com.thinkingcoder.tcrpc.core.registry.RegistryCenter;
import com.thinkingcoder.tcrpc.core.registry.tc.TcRegistryCenter;
import com.thinkingcoder.tcrpc.core.transport.SpringBootTransport;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@Import({AppProperties.class, ProviderProperties.class, SpringBootTransport.class})
public class ProviderConfig {

    @Value("${server.port:9090}")
    private String port;

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "apollo.bootstrap", value = "enabled")
    ApolloChangedListener providerApolloChangedListener() {
        return new ApolloChangedListener();
    }

    @Bean
    ProviderBootstrap providerBootstrap(@Autowired AppProperties appProperties,
        @Autowired ProviderProperties providerProperties) {
        return new ProviderBootstrap(this.port, appProperties, providerProperties);
    }

    @Bean
    ProviderInvoker providerInvoker(@Autowired ProviderBootstrap providerBootstrap) {
        return new ProviderInvoker(providerBootstrap);
    }

    @Bean
    @Order(Integer.MIN_VALUE)
    public ApplicationRunner providerBootstrapRunner(@Autowired ProviderBootstrap providerBootstrap) {
        return x -> {
            log.info("providerBootstrap starting ...");
            providerBootstrap.start();
            log.info("providerBootstrap started ...");
        };
    }

    @Bean
    @ConditionalOnMissingBean
    public RegistryCenter providerRegistryCenter() {
        return new TcRegistryCenter();
    }

}
